package com.atzxh.heima.netty.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

import static com.atzxh.heima.netty.c1.ByteBufferUtil.debugAll;

/**
 * @author 小红同学
 * @date 2023-12-15-21:22
 * @description     多线程版本
 */
@Slf4j
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        Selector boss = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8088));
        SelectionKey selectionKey = ssc.register(boss, 0, null);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);
        // 1、创建固定的worker并且初始化
        Worker worker = new Worker("worker-01");

        while (true) {
            boss.select();
            Iterator<SelectionKey> keyIterator = boss.selectedKeys().iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                keyIterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = ssc.accept();
                    log.debug("connected....{}",socketChannel.getRemoteAddress());
                    socketChannel.configureBlocking(false);
                    // 2、注册到selector
                    log.debug("before registered....{}",socketChannel.getRemoteAddress());
                    worker.register(socketChannel);
                    log.debug("after registered....{}",socketChannel.getRemoteAddress());
                }
            }
        }

    }

    static class Worker implements Runnable{
        private String name;
        private Thread thread;
        private Selector selector;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
        private volatile boolean start = false;

        public Worker(String name) {
            this.name = name;
        }

        public void register(SocketChannel socketChannel) throws IOException {
            // 使用 start 作为标识，使 thread 和 selector 只被初始化一次
            if (!start) {
                thread = new Thread(this,name);
                thread.start();
                selector = Selector.open();
                start = true;
            }
            // 向队列添加任务， 但该任务不会立刻被执行
            queue.add(()->{
                try {
                    socketChannel.register(selector,SelectionKey.OP_READ,null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();
        }
        @Override
        public void run() {
            while (true) {
                try {
                    selector.select(); // worker-01
                    Runnable task = queue.poll();
                    if (task != null) {
                        // 此时执行队列任务
                        task.run();
                    }
                    Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                    while (keyIterator.hasNext()) {
                        SelectionKey key = keyIterator.next();
                        keyIterator.remove();
                        if (key.isReadable()) {
                            try {
                                ByteBuffer byteBuffer = ByteBuffer.allocate(16);
                                SocketChannel channel = (SocketChannel) key.channel();
                                log.debug("before read....{}",channel.getRemoteAddress());
                                int read = channel.read(byteBuffer);
                                if (read == -1) {
                                    key.cancel();
                                } else {
                                    byteBuffer.flip();
                                    debugAll(byteBuffer);
                                }
                            } catch (IOException ex) {
                                ex.printStackTrace();
                                key.cancel();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }
    }
}
